import React, { Component } from 'react';

import LoginService from 'services/Login';

import { trimSpace } from 'utils/tools';

import './index.scss';

const loginService = new LoginService();


class LoginForm extends Component {
  constructor (props) {
    super(props);

    this.state = {
      username: '',
      password: ''
    }
  }

  /* 挂载周期函数*/
  componentDidMount () {
    this.loginCheck();
  }

  /* 检查登录状态，登录时自动跳转首页*/
  async loginCheck () {
    const result = await loginService.loginCheck();
    const errorCode = result.error_code;
    if(errorCode === 10007) {
        //登录状态
        const  {history} = this.props;
        history.push('/');
    }
  }

  onInputTyping (e) {
    //通过id区分不同的输入框
    const id = e.target.id,
        val = e.target.value;
    this.setState({
      [id]: val  
    }, ()=> {
      //设置成功后的回调
      // console.log(this.state.username, this.state.password);
    })
  }

  /* 提交数据*/
  async onLoginSubmit (e) {
    const { username, password } = this.state;
    if(trimSpace(username).length <= 0) {
      alert('用户名长度不正确');
      return;
    }

    if(trimSpace(password).length <= 0) {
      alert('密码长度不正确');
      return;
    }

    const result = await loginService.loginAction({
      username: trimSpace(username),
      password: trimSpace(password)
    })

    const errorCode = result.error_code,
          errorMsg = result.error_msg;

    if(errorCode !== 0 ) {
      alert(errorMsg + '(errorCode: ' + errorCode + ')' );
      return;
    }

    alert('登录成功');
    
    //跳转
    const { history } = this.props;
    history.push('/');
  }

  render () {
    return (
      <div className="login-form-wrapper">
        <div className="input-box">
          <label htmlFor="username" className="iconfont iconicon"></label>
          <input id="username" className="login-input" type="text" placeholder="管理员用户名" 
            onChange={ (e) => this.onInputTyping(e) }/>
        </div>
        <div className="input-box">
          <label htmlFor="password" className="iconfont iconxiangce"></label>
          <input id="password" className="login-input" type="text" placeholder="管理员密码"
            onChange={ (e) => this.onInputTyping(e) } />
        </div>
        <div className="input-box">
          <button className="btn btn-primary"
            onClick ={ (e) => this.onLoginSubmit(e) }>登录后台</button>
        </div>
      </div>
    )
  }
}

export default LoginForm;